<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.title" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入公告标题查询"></el-input>
      <el-select v-model="data.queryStatus" style="width: 240px; margin-right: 10px" placeholder="请选择公告状态">
        <el-option label="全部" value=""></el-option>
        <el-option label="草稿" value="0"></el-option>
        <el-option label="已发布" value="1"></el-option>
        <el-option label="已归档" value="2"></el-option>
      </el-select>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="公告标题">
          <template v-slot="scope">
            <span @click="preview(scope.row)" style="cursor: pointer; color: #409EFF">{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdByUsername" label="发布人" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="time" label="发布时间" />
        <el-table-column prop="updatedByUsername" label="最后修改人" />
        <el-table-column prop="updatedTime" label="最后修改时间" />
        <el-table-column prop="status" label="状态">
          <template v-slot="scope">
            <span :class="getStatusClass(scope.row.status)">{{ getStatusText(scope.row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
            <el-button type="success" circle :icon="View" @click="preview(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize"
                     v-model:current-page="data.pageNum" :total="data.total"/>
    </div>

    <el-dialog title="公告信息" v-model="data.formVisible" width="60%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="title" label="公告标题">
          <el-input v-model="data.form.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item prop="noticeImg" label="公告图片">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :on-success="handleFileUpload"
              list-type="picture"
          >
            <img v-if="data.form.noticeImg" :src="data.form.noticeImg" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item prop="content" label="公告内容">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.content"
                :mode="mode"
                :default-config="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item prop="status" label="公告状态">
          <el-select v-model="data.form.status" placeholder="请选择公告状态">
            <el-option label="草稿" value="0"></el-option>
            <el-option label="已发布" value="1"></el-option>
            <el-option label="已归档" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="data.form.remark" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="公告预览" v-model="data.previewVisible" width="60%" destroy-on-close>
      <div v-if="data.selectedRow" style="width: 100%; margin: 30px auto">
        <div style="font-size: 20px; font-weight: bold; text-align: center">{{ data.selectedRow.title }}</div>
        <div style="margin-top: 15px; color: #666666; text-align: center">
          <span style="margin-left: 30px">发布人：{{ data.selectedRow.createdByUsername }}</span>
          <span style="margin-left: 30px"
                v-if="data.selectedRow.createdByUsername !== data.selectedRow.updatedByUsername">
            最后修改人：{{ data.selectedRow.updatedByUsername }}
          </span>
          <br/>
          <span style="margin-left: 30px">发布时间：{{ data.selectedRow.time }}</span>
          <span style="margin-left: 30px" v-if="data.selectedRow.updatedTime !== data.selectedRow.time">
            最后修改时间：{{ data.selectedRow.updatedTime }}<br/>
          </span>
          <br/>
          <span style="margin-left: 30px">状态：<span :class="getStatusClass(data.selectedRow.status)">{{
              getStatusText(data.selectedRow.status)
            }}</span></span>
          <br/>
          <span style="margin-left: 30px">备注：{{ data.selectedRow.remark }}</span>
        </div>
        <div v-if="data.selectedRow.noticeImg" style="text-align: center; margin-top: 30px;">公告图片：
          <img :src="data.selectedRow.noticeImg" alt="公告图片" class="avatar" />
        </div>公告内容：
        <div style="margin-top: 50px" v-html="data.selectedRow.content" class="rich-text-preview"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Plus, View } from "@element-plus/icons-vue";
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

const baseUrl = import.meta.env.VITE_BASE_URL;

const data = reactive({
  user: JSON.parse(localStorage.getItem('user') || '{}'),
  formVisible: false,
  previewVisible: false,
  form: {
    status: '0',
    remark: ''
  },
  selectedRow: {},
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  title: null,
  queryStatus: '',
  ids: []
});

const editorRef = ref(null);
const mode = 'simple';

const editorConfig = {
  MENU_CONF: {
    uploadImage: {
      headers: {
        token: data.user.token,
      },
      server: 'http://localhost:8080/files/wang/upload',
      fieldName: 'file'
    }
  }
};

const handleFileUpload = (response) => {
  data.form.noticeImg = response.data;
};

const handleCreated = (editor) => {
  editorRef.value = editor;
};

const load = () => {
  request.post('/notice/selectPageByAdmin', {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    title: data.title,
    noticeCategory: 0,
    status: data.queryStatus
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || [];
      data.total = res.data?.total;
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    console.error("Error loading notices:", err);
    ElMessage.error("加载公告失败，请稍后再试");
  });
};

const handleAdd = () => {
  data.form = {
    title: '',
    content: '',
    status: '0',
    remark: ''
  };
  data.formVisible = true;
};

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.form.status = String(data.form.status);
  data.formVisible = true;
};

const add = () => {
  data.form.noticeCategory = 0;
  request.post('/notice/add', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const update = () => {
  data.form.noticeCategory = 0;
  request.put('/notice/update', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const save = () => {
  data.form.id ? update() : add();
};

const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(() => {
    request.delete('/notice/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(() => {
    request.delete("/notice/delete/batch", {data: data.ids}).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id);
};

const reset = () => {
  data.title = null;
  data.queryStatus = '';
  load();
};

const preview = (row) => {
  request.get(`/notice/selectById/${row.id}`).then(res => {
    if (res.code === '200') {
      data.selectedRow = res.data;
      console.log('Selected Row:', data.selectedRow); // 添加调试信息
      data.previewVisible = true;
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    console.error("Error fetching notice details:", err);
    ElMessage.error("获取公告详情失败，请稍后再试");
  });
};

const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '草稿';
    case 1:
      return '已发布';
    case 2:
      return '已归档';
    default:
      return '未知';
  }
};

const getStatusClass = (status) => {
  switch (status) {
    case 0:
      return 'draft-status';
    case 1:
      return 'published-status';
    case 2:
      return 'archived-status';
    default:
      return '';
  }
};

onMounted(() => {
  load();
});
</script>

<style scoped>
.card {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
}

.el-tag {
  margin-right: 5px;
}

.cursor-pointer {
  cursor: pointer;
  color: #409EFF;
}

.rich-text-preview img {
  max-width: 100%;
  height: auto;
}

.draft-status {
  color: #E6A23C; /* Orange for Draft */
}

.published-status {
  color: #67C23A; /* Green for Published */
}

.archived-status {
  color: #909399; /* Grey for Archived */
}

.avatar {
  width: 200px; /* 固定宽度 */
  height: 200px; /* 固定高度 */
  object-fit: cover; /* 保持图片比例并裁剪 */
}
</style>



